/* global window */
import { router } from 'utils'
import { stringify } from 'qs'
import store from 'store'
// import { ROLE_TYPE } from 'utils/constant'
import { pathMatchRegexp } from 'utils'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import api from 'api'
import { message } from 'antd'
import { pageModel, model } from 'utils/model'
import modelExtend from 'dva-model-extend'

// import {
//   Realtime,
//   TextMessage,
//   Event,
//   TypedMessage,
//   messageType,
//   messageField,
// } from 'leancloud-realtime'

const {
  queryRouteList,
  logoutUser,
  queryUserInfo,
  getUnReadMsgs,
  clearAllunread,
  clearUnread,
  ImOnline,
} = api
const regionstate = {
  isMobile: false,
  user: {},
  massageList: [],
  permissions: {
    visit: [],
  },
  routeList: [
    {
      id: '1',
      icon: 'laptop',
      name: 'Dashboard',
      zhName: '仪表盘',
      router: '/dashboard',
    },
  ],
  locationPathname: '',
  locationQuery: {},
  theme: store.get('theme') || 'light',
  collapsed: store.get('collapsed') || false,
  notifications: [],
  devicelink: undefined,
  clientWidth: document.body.clientWidth,
  clientHeight: document.body.clientHeight,
}
export default modelExtend(model, {
  namespace: 'app',
  state: {
    ...regionstate,
    theme: store.get('theme') || 'light',
    collapsed: store.get('collapsed') || false,
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        if (location) {
          dispatch({
            type: 'updateState',
            payload: {
              locationPathname: location.pathname,
              locationQuery: location.query,
            },
          })
        }
      })
    },

    setupRequestCancel({ history }) {
      history.listen(() => {
        const { cancelRequest = new Map() } = window

        cancelRequest.forEach((value, key) => {
          try {
            if (value.pathname !== window.location.pathname) {
              value.cancel(CANCEL_REQUEST_MESSAGE)
              cancelRequest.delete(key)
            }
          } catch {}
        })
      })
    },

    setup({ dispatch }) {
      dispatch({ type: 'query' })
      // var socket = atmosphere;
      // var transport = 'websocket';
      // var subSocket;
      // var request = {
      //   url: 'ws:/localhost:7000/chat',
      //   contentType: "application/json",
      //   trackMessageLength: true,
      //   shared: true,
      //   transport: transport,
      //   fallbackTransport: 'long-polling'
      // };

      // request.onOpen = function (response) {
      //   console.log('Atmosphere connected using ' + response.transport);
      //   //input.removeAttr('disabled').focus();
      //   //status.text('Choose name:');
      //   transport = response.transport;

      //   /*if (response.transport == "local") {
      //     subSocket.pushLocal("Name?");
      //   }*/
      // };

      // request.onTransportFailure = function (errorMsg, request) {
      //   //jQuery.atmosphere.info(errorMsg);
      //   /*if (window.EventSource) {
      //     request.fallbackTransport = "sse";
      //     transport = "see";
      //   }*/
      //   console.log(' errorMsg: ' + errorMsg);
      //   console.log(' request.fallbackTransport : ' + request.fallbackTransport);

      //   //header.html($('<h3>', { text: 'Atmosphere Chat. Default transport is WebSocket, fallback is ' + request.fallbackTransport }));
      // };

      // request.onMessage = function (response) {
      //   //if (!myName) return;
      //   var message = response.responseBody;
      //   try {
      //     var json = JSON.parse(message);
      //   } catch (e) {
      //     console.log('This doesn\'t look like a valid JSON: ', message.data);
      //     return;
      //   }

      //   //if (!logged) {
      //   //logged = true;
      //   //status.text(myName + ': ').css('color', 'blue');
      //   //input.removeAttr('disabled').focus();
      //   // subSocket.pushLocal(myName);
      //   //} else {
      //   //input.removeAttr('disabled');

      //   var me = json.author == author;
      //   var date = typeof (json.time) == 'string' ? parseInt(json.time) : json.time;
      //   console.log(json.author + ":" + json.message + "," + new Date(date));
      //   //}
      // };

      // request.onClose = function (response) {
      //   console.log('onClose');
      // }

      // subSocket = socket.subscribe(request);
      //dispatch({ type: "updateState", payload: { subSocket: ws } })
    },
  },
  effects: {
    *query({ payload }, { call, put, select }) {
      let result = {}
      const { locationPathname } = yield select(_ => _.app)
      try {
        result = yield call(queryUserInfo, payload)
      } catch {
        // console.log("错误");
        router.push({
          pathname: '/login',
          search: stringify({
            from: locationPathname,
          }),
        })
        return
      }
      const { success, user, dashboard } = result.result
      if (success && user) {
        try {
          const resultlist = yield call(queryRouteList)
          const { permissions } = user
          const list = resultlist.result
          let routeList = list
          permissions.visit = list.map(item => item.id)
          yield put({
            type: 'updateState',
            payload: {
              user,
              permissions,
              routeList,
            },
          })
          yield put({ type: 'getUnreadMsg' })
        } catch {
          yield put({
            type: 'updateState',
            payload: {
              user,
              permissions: { visit: [] },
              menu: [
                {
                  id: '1',
                  icon: 'laptop',
                  name: 'No Permission',
                  zhName: '无权限',
                  router: '/dashboard',
                },
              ],
            },
          })
        }
        if (pathMatchRegexp(['/', '/login'], window.location.pathname)) {
          router.push({
            pathname: `/${dashboard}`,
          })
        }
        // if (
        //   permissions.role === ROLE_TYPE.ADMIN ||
        //   permissions.role === ROLE_TYPE.DEVELOPER
        // ) {
        //   permissions.visit = list.map(item => item.id)
        // } else {
        //   routeList = list.filter(item => {
        //     const cases = [
        //       permissions.visit.includes(item.id),
        //       item.mpid
        //         ? permissions.visit.includes(item.mpid) || item.mpid === '-1'
        //         : true,
        //       item.bpid ? permissions.visit.includes(item.bpid) : true,
        //     ]
        //     return cases.every(_ => _)
        //   })
        // }
      } else {
        //if (queryLayout(config.layouts, locationPathname) !== 'public') {
        // console.log(JSON.stringify(result));
        router.push({
          pathname: '/login',
          search: stringify({
            from: locationPathname,
          }),
        })
      }
    },

    *signOut({ payload }, { call, put }) {
      yield call(logoutUser)
      store.remove('mr-ly-sessionToken')
      sessionStorage.removeItem('mr-ly-sessionToken-session')
      yield put({
        type: 'updateState',
        payload: {
          user: {},
          notifications: [],
          permissions: { visit: [] },
          menu: [
            {
              id: '1',
              icon: 'laptop',
              name: 'Dashboard',
              zhName: '首页',
              router: '/dashboard',
            },
          ],
        },
      })
      yield put({ type: 'socket/closeWs' })
      yield put({ type: 'query' })
    },

    *getUnreadMsg({ payload }, { call, put }) {
      const { result } = yield call(getUnReadMsgs)
      yield put({ type: 'updateState', payload: { notifications: result } })
      // console.log("getUnreadMsg:" + JSON.stringify(result));
    },

    *clearAllunread({ payload }, { call, put, select }) {
      message.loading('清除中...', 0)
      yield call(clearAllunread)
      // yield put({ type: 'getUnreadMsg' })
      message.destroy()
      message.success('清除成功！')
    },

    *clearUnread({ payload }, { call, put, select }) {
      message.loading('清除中...', 0)
      yield call(clearUnread, payload)
      // yield put({ type: 'getUnreadMsg' })
      message.destroy()
      message.success('清除成功！')
    },
  },
  reducers: {
    handleThemeChange(state, { payload }) {
      store.set('theme', payload)
      state.theme = payload
    },

    handleCollapseChange(state, { payload }) {
      store.set('collapsed', payload)
      state.collapsed = payload
    },

    allNotificationsRead(state) {
      state.notifications = []
    },

    setMobile(state, { payload }) {
      state.isMobile = payload
    },
  },
})
